import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/services.dart';
// import 'package:image_saver/image_saver.dart';
// import 'package:image_picker_saver/image_picker_saver.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:typed_data';
import 'package:r_album/r_album.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import '../util/Toast.dart';
import '../entity/article_list_entity.dart';
import '../http/Api.dart';
import '../http/HttpUtil.dart';
import '../util/AppSaveInfoUtil.dart';
import '../util/SignUtil.dart';
import '../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter/services.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import '../liz_home/goods/GoodsDetail.dart';
import 'package:flutter_aygsh/entity/banner_entity.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../liz_mine/set/SCVideo.dart';
import '../util/PreviewImagesWidget.dart';
import 'package:path_provider/path_provider.dart';
import '../util/LoadingUtil.dart';

class MaterialCenterPage extends StatefulWidget {
  int type = 0;
  MaterialCenterPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MaterialCenterView();
  }
}

class MaterialCenterView extends State<MaterialCenterPage>
    with WidgetsBindingObserver {
  List<HomeListDataData> dataList = new List();
  int page = 1;
  String token = "";
  EasyRefreshController _controller = new EasyRefreshController();
  List cates = [];
  int groupValue = 0;
  String cat_id = '';
  String type_choose = '';
  List<BannerModelData> bannerData;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      // appBar: new AppBar(
      //   title: new Text(
      //     "素材",
      //     style: TextStyle(
      //         fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
      //         color: Colors.black),
      //   ),
      //   elevation: 0.5,
      //   backgroundColor: Colors.white,
      //   brightness: Brightness.light,
      //   centerTitle: true,
      //   iconTheme: new IconThemeData(color: Colors.black),
      // ),
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.dark,
        child: new Container(
            margin: EdgeInsets.only(top: kWindowstateHeight),
            color: white,
            child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: CustomScrollView(
                slivers: <Widget>[
                  SliverToBoxAdapter(child: initTop()),
                  SliverToBoxAdapter(
                    child: cates.length > 0
                        ? Container(
                            //横向滑动列表
                            color: Colors.white,
                            margin: EdgeInsets.fromLTRB(
                              0,
                              kMargin10,
                              0,
                              kMargin10,
                            ),
                            padding: EdgeInsets.fromLTRB(
                              kMargin10,
                              0,
                              kMargin10,
                              0,
                            ),
                            height: ScreenUtil.getInstance().setHeight(DP_50),
                            child: ListView.builder(
                              scrollDirection: Axis.horizontal,
                              itemCount: cates.length,
                              itemBuilder: (context, index) {
                                return zdGrid(context, index);
                              },
                            ))
                        : Visibility(
                            visible: true,
                            child: Container(width: 0, height: 0),
                          ),
                  ),
                  type_choose == '3'
                      ? SliverGrid(
                          gridDelegate:
                              SliverGridDelegateWithMaxCrossAxisExtent(
                            maxCrossAxisExtent:
                                ScreenUtil.getInstance().setWidth(750) / 3,
                            mainAxisSpacing: 0,
                            crossAxisSpacing: 0,
                            childAspectRatio: 0.7, //子控件宽高比
                          ),
                          delegate: SliverChildBuilderDelegate(
                            (BuildContext context, int index) {
                              return dataList.length > 0
                                  ? _renderRow3(context, index)
                                  : Container();
                            },
                            childCount: dataList.length,
                          ),
                        )
                      : SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) {
                              if (dataList.length > 0) {
                                return type_choose == '1'
                                    ? _renderRow(context, index)
                                    : (type_choose == '2'
                                        ? _renderRow2(context, index)
                                        : (_renderRow4(context, index)));
                              } else {
                                return Visibility(
                                  visible: true,
                                  child: Container(width: 0, height: 0),
                                );
                              }
                            },
                            childCount: dataList.length,
                          ),
                        )
                ],
              ),
              onRefresh: () async {
                dataList.clear();
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            )),
      ),
    );
  }

  initTop() {
    //轮播图
    return Container(
        // padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setHeight(DP_30),
        //     0, ScreenUtil.getInstance().setHeight(DP_30), 0),
        margin: EdgeInsets.fromLTRB(0, 0, 0, kMargin20),
        height: (MediaQuery.of(context).size.width -
                ScreenUtil.getInstance().setHeight(DP_60)) /
            2.4,
        child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            return new ClipRRect(
              child:
                  bannerData[index].img == null || bannerData[index].img == ''
                      ? Image.asset('images/pic_default.png')
                      : CachedNetworkImage(
                          fit: BoxFit.fill,
                          imageUrl: Api.BaseUrl +
                              'public/upload/' +
                              bannerData[index].img.replaceAll('\\', '/'),
                          placeholder: (context, url) =>
                              Image.asset('images/pic_default.png'),
                          errorWidget: (context, url, error) =>
                              Image.asset('images/pic_default.png'),
                        ),
              borderRadius: BorderRadius.circular(0.0),
            );
          },
          itemCount: bannerData == null ? 0 : bannerData.length,
          pagination: new SwiperPagination(
              builder: DotSwiperPaginationBuilder(
                  color: Colors.grey,
                  activeColor: Colors.blue,
                  size: 7.0,
                  activeSize: 7.0)),
          scrollDirection: Axis.horizontal,
          autoplay: true,
          onIndexChanged: (index) {
            setState(() {});
          },
          onTap: (index) {},
        ));
  }

//样式1
  // 商品链接+宣传+图片+可复制文本
  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: Column(
        children: <Widget>[
          Container(
            color: white,
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Container(
                      height: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                      width: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                      padding: EdgeInsets.all(1),
                      child: ClipOval(
                        child: Image.asset(
                          "images/logo.png",
                          width: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                          height: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                        ),
                      ),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(
                              ScreenUtil.getInstance().setHeight(DP_60 + 5)),
                          border: Border.all(color: white, width: 1)),
                    ),
                    Container(width: ScreenUtil.getInstance().setHeight(DP_20)),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          dataList[index].author_name,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Container(
                            height:
                                ScreenUtil.getInstance().setHeight(DP_8 / 2)),
                        Text(
                          dataList[index].pubtime,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color: Colors.black45),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                    Expanded(
                      child: Center(),
                    ),
                    new Container(
                      width: ScreenUtil.getInstance().setWidth(DP_120 + DP_20),
                      padding: EdgeInsets.all(2),
                      decoration: new BoxDecoration(
                          color: Colors.red[50],
                          borderRadius: BorderRadius.circular(10)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Image.asset("images/icon_share.png"),
                          Container(
                            width: ScreenUtil.getInstance().setHeight(DP_10),
                          ),
                          new Text(
                            dataList[index].clicknum,
                            style: new TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
                dataList[index].goods_id == null
                    ? Container()
                    : GestureDetector(
                        onTap: () {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (context) {
                            return GoodsDetailPage(
                              goods_id: dataList[index].goods_id.toString(),
                              img: dataList[index].img,
                            );
                          }));
                        },
                        child: Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_15)),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(3),
                              color: f0Color),
                          child: Row(
                            children: <Widget>[
                              ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: dataList[index].goods_img == null ||
                                        dataList[index].goods_img == ''
                                    ? Image.asset('images/pic_default.png')
                                    : CachedNetworkImage(
                                        fit: BoxFit.cover,
                                        width: ScreenUtil.getInstance()
                                            .setHeight(DP_60 + 10),
                                        height: ScreenUtil.getInstance()
                                            .setHeight(DP_60 + 10),
                                        imageUrl: Api.ImgBaseUrl +
                                            dataList[index].goods_img,
                                        placeholder: (context, url) =>
                                            Image.asset(
                                                'images/pic_default.png'),
                                        errorWidget: (context, url, error) =>
                                            Image.asset(
                                                'images/pic_default.png'),
                                      ),
                              ),
                              Container(
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_15)),
                              Expanded(
                                child: Text(
                                  dataList[index].goods_name,
                                  maxLines: 2,
                                  style: TextStyle(
                                      letterSpacing: 2,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(MINI_FONT_SIZE),
                                      color: black_99),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              Container(
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_15)),
                              Icon(Icons.arrow_forward_ios,
                                  color: Colors.black45,
                                  size:
                                      ScreenUtil.getInstance().setHeight(DP_30))
                            ],
                          ),
                        )),
                Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
                Html(
                  defaultTextStyle:
                      TextStyle(color: black_99, letterSpacing: 2),
                  data: dataList[index].content == null
                      ? ""
                      : dataList[index].content,
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
                GridView.builder(
                  shrinkWrap: true,
                  padding: EdgeInsets.only(top: 0),
                  physics: new NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing:
                          ScreenUtil.getInstance().setHeight(DP_10),
                      crossAxisSpacing:
                          ScreenUtil.getInstance().setHeight(DP_10),
                      childAspectRatio: 1),
                  itemBuilder: (BuildContext context, int index1) {
                    List m = dataList[index].imglists;
                    String m2 = m[index1].replaceAll('{img:', '');
                    String m3 = m2.replaceAll('}', '');
                    // print('=======2');
                    // print(m2);
                    return GestureDetector(
                      child: CachedNetworkImage(
                        width: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_60)) /
                            3,
                        height: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_60)) /
                            3,
                        fit: BoxFit.cover,
                        imageUrl: Api.ImgBaseUrl + m3,
                        placeholder: (context, url) =>
                            Image.asset('images/pic_default.png'),
                        errorWidget: (context, url, error) =>
                            Image.asset('images/pic_default.png'),
                      ),
                      onTap: () {
                        print(dataList[index].imglists);
                        List<String> imgs = new List();
                        for (int i = 0;
                            i < dataList[index].imglists.length;
                            i++) {
                          String m2 = dataList[index]
                              .imglists[i]
                              .replaceAll('{img:', '');
                          String m3 = m2.replaceAll('}', '');
                          imgs.add(Api.ImgBaseUrl + m3);
                        }
                        Navigator.of(context).push(PageRouteBuilder(
                            pageBuilder: (c, a, s) => PreviewImagesWidget(
                                  imgs,
                                  initialPage: index1,
                                )));
                      },
                    );
                  },
                  itemCount: dataList[index].imglists.length > 9
                      ? 9
                      : dataList[index].imglists.length,
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_15)),

                // Container(height: ScreenUtil.getInstance().setHeight(DP_15)),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Center(),
                    ),
                    new GestureDetector(
                        onTap: () {
                          Clipboard.setData(
                              ClipboardData(text: dataList[index].content));
                          _save(dataList[index].imglists);
                        },
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(15),
                              3,
                              ScreenUtil.getInstance().setHeight(15),
                              3),
                          decoration: new BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10)),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset("images/icon_forward.png"),
                              Container(
                                width: ScreenUtil.getInstance().setHeight(5),
                              ),
                              new Text(
                                "分享",
                                style: new TextStyle(
                                    color: white,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(MINI_FONT_SIZE)),
                              ),
                            ],
                          ),
                        ))
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: ScreenUtil.getInstance().setHeight(DP_15),
            color: divideColor,
          ),
        ],
      ),
      onTap: () {
        // HomeListDataData model = dataList[index];
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new SCVideoPage(
        //     model: model,
        //   );
        // }));
      },
    );
  }

//样式2 宣传+图片+商品链接
  Widget _renderRow2(BuildContext context, int index) {
    return new GestureDetector(
      child: Column(
        children: <Widget>[
          Container(
            color: white,
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Container(
                      height: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                      width: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                      padding: EdgeInsets.all(1),
                      child: ClipOval(
                        child: Image.asset(
                          "images/logo.png",
                          width: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                          height: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                        ),
                      ),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(
                              ScreenUtil.getInstance().setHeight(DP_60 + 5)),
                          border: Border.all(color: white, width: 1)),
                    ),
                    Container(width: ScreenUtil.getInstance().setHeight(DP_20)),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          dataList[index].author_name,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Container(
                            height:
                                ScreenUtil.getInstance().setHeight(DP_8 / 2)),
                        Text(
                          dataList[index].pubtime,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color: Colors.black45),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                    Expanded(
                      child: Center(),
                    ),
                    new Container(
                      width: ScreenUtil.getInstance().setWidth(DP_120 + DP_20),
                      padding: EdgeInsets.all(2),
                      decoration: new BoxDecoration(
                          color: Colors.red[50],
                          borderRadius: BorderRadius.circular(10)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Image.asset("images/icon_share.png"),
                          Container(
                            width: ScreenUtil.getInstance().setHeight(DP_10),
                          ),
                          new Text(
                            dataList[index].clicknum,
                            style: new TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
                Html(
                  defaultTextStyle:
                      TextStyle(color: black_99, letterSpacing: 2),
                  data: dataList[index].content == null
                      ? ""
                      : dataList[index].content,
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
                GridView.builder(
                  shrinkWrap: true,
                  padding: EdgeInsets.only(top: 0),
                  physics: new NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing:
                          ScreenUtil.getInstance().setHeight(DP_10),
                      crossAxisSpacing:
                          ScreenUtil.getInstance().setHeight(DP_10),
                      childAspectRatio: 1),
                  itemBuilder: (BuildContext context, int index1) {
                    List m = dataList[index].imglists;
                    // print('=======1');
                    // print(m);
                    String m2 = m[index1].replaceAll('{img:', '');
                    String m3 = m2.replaceAll('}', '');
                    // print('=======2');
                    // print(m2);
                    return GestureDetector(
                      child: CachedNetworkImage(
                        width: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_60)) /
                            3,
                        height: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_60)) /
                            3,
                        fit: BoxFit.cover,
                        imageUrl: Api.ImgBaseUrl + m3,
                        placeholder: (context, url) =>
                            Image.asset('images/pic_default.png'),
                        errorWidget: (context, url, error) =>
                            Image.asset('images/pic_default.png'),
                      ),
                      onTap: () {
                        print(dataList[index]);
                        List<String> imgs = new List();
                        for (int i = 0;
                            i < dataList[index].imglists.length;
                            i++) {
                          String m2 = dataList[index]
                              .imglists[i]
                              .replaceAll('{img:', '');
                          String m3 = m2.replaceAll('}', '');
                          imgs.add(Api.ImgBaseUrl + m3);
                        }
                        Navigator.of(context).push(PageRouteBuilder(
                            pageBuilder: (c, a, s) => PreviewImagesWidget(
                                  imgs,
                                  initialPage: index1,
                                )));
                      },
                    );
                  },
                  itemCount: dataList[index].imglists.length > 9
                      ? 9
                      : dataList[index].imglists.length,
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_15)),
                dataList[index].goods_id == null
                    ? Container()
                    : GestureDetector(
                        onTap: () {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (context) {
                            return GoodsDetailPage(
                              goods_id: dataList[index].goods_id.toString(),
                              img: dataList[index].img,
                            );
                          }));
                        },
                        child: Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_15)),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(3),
                              color: f0Color),
                          child: Row(
                            children: <Widget>[
                              ClipRRect(
                                  borderRadius: BorderRadius.circular(5),
                                  child: dataList[index].goods_img == null ||
                                          dataList[index].goods_img == ''
                                      ? Image.asset('images/pic_default.png')
                                      : CachedNetworkImage(
                                          width: ScreenUtil.getInstance()
                                              .setHeight(DP_60 + 10),
                                          fit: BoxFit.cover,
                                          height: ScreenUtil.getInstance()
                                              .setHeight(DP_60 + 10),
                                          imageUrl: Api.ImgBaseUrl +
                                              dataList[index].goods_img,
                                          placeholder: (context, url) =>
                                              Image.asset(
                                                  'images/pic_default.png'),
                                          errorWidget: (context, url, error) =>
                                              Image.asset(
                                                  'images/pic_default.png'),
                                        )),
                              Container(
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_15)),
                              Expanded(
                                child: Text(
                                  dataList[index].goods_name,
                                  maxLines: 2,
                                  style: TextStyle(
                                      letterSpacing: 2,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(MINI_FONT_SIZE),
                                      color: black_99),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              Container(
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_15)),
                              Icon(Icons.arrow_forward_ios,
                                  color: Colors.black45,
                                  size:
                                      ScreenUtil.getInstance().setHeight(DP_30))
                            ],
                          ),
                        ),
                      ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_15)),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Center(),
                    ),
                    new GestureDetector(
                        onTap: () {
                          Clipboard.setData(
                              ClipboardData(text: dataList[index].content));
                          _save(dataList[index].imglists);
                        },
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(15),
                              3,
                              ScreenUtil.getInstance().setHeight(15),
                              3),
                          decoration: new BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10)),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset("images/icon_forward.png"),
                              Container(
                                width: ScreenUtil.getInstance().setHeight(5),
                              ),
                              new Text(
                                "分享",
                                style: new TextStyle(
                                    color: white,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(MINI_FONT_SIZE)),
                              ),
                            ],
                          ),
                        ))
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: ScreenUtil.getInstance().setHeight(DP_15),
            color: divideColor,
          ),
        ],
      ),
      onTap: () {
        // HomeListDataData model = dataList[index];
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new SCVideoPage(
        //     model: model,
        //   );
        // }));
      },
    );
  }

//样式3 宣传海报
  Widget _renderRow3(BuildContext context, int index) {
    return dataList[index].img == null || dataList[index].img == ''
        ? Image.asset('images/pic_default.png')
        : CachedNetworkImage(
            width: (MediaQuery.of(context).size.width -
                    ScreenUtil.getInstance().setHeight(DP_80 - 10)) /
                3,
            fit: BoxFit.fill,
            height: 10 *
                (MediaQuery.of(context).size.width -
                    ScreenUtil.getInstance().setHeight(DP_80 - 10)) /
                3 /
                6,
            imageUrl: Api.ImgBaseUrl + dataList[index].img,
            placeholder: (context, url) =>
                Image.asset('images/pic_default.png'),
            errorWidget: (context, url, error) =>
                Image.asset('images/pic_default.png'),
          );
  }

//样式4 视频列表
  Widget _renderRow4(BuildContext context, int index) {
    return GestureDetector(
        onTap: () {
          HomeListDataData model = dataList[index];
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return new SCVideoPage(
              model: model,
            );
          }));
        },
        child: Container(
          margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              0),
          decoration: BoxDecoration(
              color: white,
              borderRadius: BorderRadius.circular(
                  ScreenUtil.getInstance().setHeight(DP_10))),
          child: Material(
            borderRadius: BorderRadius.circular(
                ScreenUtil.getInstance().setHeight(DP_10)),
            color: white,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                ClipRRect(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10)),
                        topLeft: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10))),
                    child: dataList[index].img == ""
                        ? Image.asset('images/app_icon.png',
                            width: MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_40),
                            fit: BoxFit.fill,
                            height: (MediaQuery.of(context).size.width -
                                    ScreenUtil.getInstance().setHeight(DP_40)) /
                                2)
                        : CachedNetworkImage(
                            fit: BoxFit.fill,
                            width: MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_40),
                            height: (MediaQuery.of(context).size.width -
                                    ScreenUtil.getInstance().setHeight(DP_40)) /
                                2,
                            imageUrl: Api.ImgBaseUrl + dataList[index].img,
                            placeholder: (context, url) => Image.asset(
                              'images/pic_default.png',
                              width: MediaQuery.of(context).size.width -
                                  ScreenUtil.getInstance().setHeight(DP_40),
                              height: (MediaQuery.of(context).size.width -
                                      ScreenUtil.getInstance()
                                          .setHeight(DP_40)) /
                                  2,
                            ),
                            errorWidget: (context, url, error) => Image.asset(
                              'images/pic_default.png',
                              width: MediaQuery.of(context).size.width -
                                  ScreenUtil.getInstance().setHeight(DP_40),
                              height: (MediaQuery.of(context).size.width -
                                      ScreenUtil.getInstance()
                                          .setHeight(DP_40)) /
                                  2,
                            ),
                          )),
                Padding(
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_8)),
                  child: Text(
                    dataList[index].title,
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                        color: black),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_15),
                      0,
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_15)),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      SizedBox(
                        width: 18 * 1.00 + 12,
                        child: Stack(
                          alignment: AlignmentDirectional.topStart,
                          children: <Widget>[
                            ClipOval(
                              child: Image.asset('images/app_icon.png',
                                  width: 30, height: 30),
                            ),
                          ],
                        ),
                      ),
                      Container(
                          width: ScreenUtil.getInstance().setHeight(DP_15)),
                      Text(dataList[index].author_name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color: Colors.black45)),
                      Expanded(
                        child: Center(),
                      ),
                      new Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(15),
                            3,
                            ScreenUtil.getInstance().setHeight(15),
                            3),
                        decoration: new BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(10)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset("images/icon_forward.png"),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(5),
                            ),
                            new Text(
                              "分享",
                              style: new TextStyle(
                                  color: white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(MINI_FONT_SIZE)),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
            elevation: 1,
          ),
        ));
  }

  Widget zdGrid(context, index) {
    var value = cates[index];
    return Container(
      alignment: Alignment.center,
      width: ScreenUtil.getInstance().setWidth(750) / 3,
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: groupValue == value['cat_id']
                ? GestureDetector(
                    child: Container(
                        // color: Colors.red,
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(width: 1, color: Colors.red))
//              border: Border.all(color: Colors.grey,width: 0.5),

//              borderRadius: BorderRadius.circular(5),
                            ),
                        alignment: Alignment.center,
                        child: Text(
                          value['cat_name'],
                          style: TextStyle(color: Colors.red),
                        )),
                    onTap: () {
                      print('切换${value}');
                      updateGroupValue(value['cat_id']);
                      setState(() {
                        type_choose = value['type_choose'].toString();
                        cat_id = value['cat_id'].toString();
                        page = 1;
                        loadList();
                      });
                    },
                  )
                : GestureDetector(
                    child: Container(
                      child: Text(value['cat_name'],
                          style: TextStyle(color: Colors.black)),
                      alignment: Alignment.center,
                    ),
                    onTap: () {
                      print('切换${value}');
                      updateGroupValue(value['cat_id']);
                      setState(() {
                        type_choose = value['type_choose'].toString();
                        cat_id = value['cat_id'].toString();
                        page = 1;
                        loadList();
                      });
                    },
                  ),
            // Container(
            //   width: kMargin10,
            //   height: 1,
            // )
          )
        ],
      ),
    );
  }

  _save(List list) async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new NetLoadingDialog(
            loadingText: "保存中...",
            bgColor: Color.fromARGB(255, 0, 0, 0),
            requestCallBack: null,
            outsideDismiss: false,
          );
        });

    for (var i = 0; i < list.length; i++) {
      String m2 = list[i].replaceAll('{img:', '');

      String m3 = m2.replaceAll('}', '');
      String url = Api.ImgBaseUrl + m3;
      print(url);

      var response = await Dio()
          .get(url, options: Options(responseType: ResponseType.bytes));
      final result =
          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      print(result);
      // Dio dio = Dio();
      //   dio.options.responseType = ResponseType.bytes;
      // var response = await dio.get(url);
      // File savedFile = await ImageSaver.toFile(fileData: Uint8List.fromList(response.data));
      //  print(savedFile.path);
      if (result == null) {
        Navigator.of(context).pop(1);
      } else {
        if (i == list.length - 1) {
          Navigator.of(context).pop(1);
          showDialog(
              context: context,
              builder: (context) {
                return new AlertDialog(
                  title: new Text("提示信息"),
                  content: new Text('图片已成功保存到相册，文案已复制'),
                  actions: <Widget>[
                    new FlatButton(
                        child: new Text("取消"),
                        onPressed: () {
                          Navigator.of(context).pop();
                        }),
                    new FlatButton(
                        child: new Text("打开微信分享"),
                        onPressed: () {
                          openwx();
                        }),
                  ],
                );
              });
        }
      }

      // Dio dio = Dio();
      //   dio.options.responseType = ResponseType.bytes;
      // var response = await dio.get(url);
      // debugPrint(response.statusCode.toString());
      // var filePath = await ImagePickerSaver.saveFile(
      //     fileData: Uint8List.fromList(response.data));

      // var savedFile= File.fromUri(Uri.file(filePath));

      // print(savedFile.path);
      // setState(() {
      //     Future<File>.sync(() => savedFile);
      // });

    }
  }

  downloadFile(urlPath, savePath) async {
    // showDialog(
    //     context: context,
    //     barrierDismissible: false,
    //     builder: (_) {
    //       return new NetLoadingDialog(
    //         loadingText: "保存中...",
    //         bgColor: Color.fromARGB(255, 0, 0, 0),
    //         requestCallBack: null,
    //         outsideDismiss: false,
    //       );
    //     });
    // Dio dio = Dio();
    // dio.options.responseType = ResponseType.bytes;
    // var response = await dio.get(urlPath);
    // File savedFile =
    //     await ImageSaver.toFile(fileData: Uint8List.fromList(response.data));
    // if (savedFile != null) Toast.toast(context, msg: "保存成功");
    // Navigator.of(context).pop(1);
  }

  openwx() async {
    const url = 'weixin://';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      const url = 'weixin://';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  }

  void updateGroupValue(int v) {
    setState(() {
      groupValue = v;
      print(v);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
    loadCateList();
    loadBanner();

    if (Platform.isIOS) {
    } else if (Platform.isAndroid) {
      Permission.storage.request();
    }
  }

  Future loadBanner() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BANNER_LIST),
      "cat_id": "4",
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANNER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print(userMap);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        _controller.finishRefresh();
        bannerData = bannerEntity.data;
      });
    }
  }

  loadCateList() async {
    Map map = new Map();
    map['pid'] = '00';
    map['sign_type'] = createSignType(Api.URL_MATERIAL_SUBCATLIST);
    Response<String> response =
        await HttpUtil().post(Api.URL_MATERIAL_SUBCATLIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print('素材分类');
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      // dataList.addAll(homeServiceEntity.data.datas);
      setState(() {
        cates = userMap['data']['list'];
        groupValue = cates[0]['cat_id'];
        cat_id = cates[0]['cat_id'].toString();
        type_choose = cates[0]['type_choose'].toString();
        loadList();
      });
    }
  }

  loadList() async {
    Map map = new Map();
    map['cat_id'] = cat_id.toString();
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = createSignType(Api.URL_MATERIAL_LIST);
    Response<String> response =
        await HttpUtil().post(Api.URL_MATERIAL_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (page == 1) {
        dataList.clear();
        _controller.resetLoadState();
        _controller.finishRefresh();
      } else {
        _controller.finishLoad(
            noMore: homeServiceEntity.data.datas.length == 0);
        if (homeServiceEntity.data.datas.length == 0) {
          // Fluttertoast.showToast(msg: "已经加载全部");
          Toast.toast(context, msg: "已经加载全部");
        }
      }
      dataList.addAll(homeServiceEntity.data.datas);
      setState(() {});
    }
  }
}
